const express = require('express'),
  router = express.Router(),
  util = require("../util/util"),
    book = require("../model/book"),
    category = require("../model/category"),
 async = require("async"),
    literature = require("../model/literature");

let reObj = util.reObj;


/**
 * @function 添加校区信息
 * @author Eric
 * @date 2018-08-01
 * @param name,code,addr,area,status
 */
router.post('/add', async (req, res) => {
    let bookid=req.body.bookid;
    let queryparam = {
      //  id: id,
      bookid:bookid
    }
    let bookparams = {
      id:bookid
    }
    try {
      let record=await literature.findOrCreate({where: queryparam,defaults: req.body})
    if (record[1]) {
      let tempRecord=await  book.findOne({where: bookparams})
      await literature.update({sortid:record[0].id,category:tempRecord.category,name:tempRecord.name,avatar:tempRecord.avatar}, {where: queryparam})
      //let updateliterature.update(req.body, {where: params})
                 console.log("tempRecord:"+JSON.stringify(tempRecord))
                 console.log("update:"+JSON.stringify(record[0]))
      res.send(reObj(0, '添加成功', record[0]))
    }
    else
    {
      res.send(reObj(-1, '记录已存在'))
    }
    } catch (error) {
      res.send(reObj(-1, '添加失败', error))
    }
    
    

})

/**
 * @function 编辑校区信息
 * @author Eric
 * @date 2018-08-01
 * @param id,name,code,addr,area,status
 */
router.post('/update', (req, res) => {
  let id = req.body.id
  let params = {
    id: id
  }

    literature.update(req.body, {where: params}).then(record => {
      console.log("upRecord"+(record))
        if (record[0] > 0) {
            res.send(reObj(0, '修改成功', record[0]))
        } else {
            res.send(reObj(-1, '无效id', []))
        }
    }).catch(err => {
        res.send(reObj(-1, '修改失败', err))
    });

})
router.post('/move', async (req, res) => {
  let upid = req.body.upid
  let downid = req.body.downid
  let upparams = {
    id: upid
  }
  let downparams = {
    id: downid
  }
  try {
    let upRecord= await literature.findOne({where: upparams})
    let downRecord= await literature.findOne({where: downparams})
    await literature.update({sortid:upRecord.sortid}, {where: {id:downRecord.id}})
    await literature.update({sortid:downRecord.sortid}, {where: {id:upRecord.id}}) 
    
    
     
  res.send(reObj(0, '更新成功', upRecord))
  } catch (error) {
    res.send(reObj(-1, '更新失败', error))
  }
  
    

})
/**
 * @function 删除对应的会议数据
 * @author Eric
 * @date 2018-07-31
 * @param id
 */
router.post('/del', (req, res) => {
  let params = {
    id: req.body.id
  }

  literature.destroy({where: params}).then(record => {
    if (record > 0) {
      res.send(reObj(0, '删除成功', record))
    } else {
      res.send(reObj(-1, '删除失败或此记录不存在', record))
    }
  }).catch(err => {
    res.send(reObj(-1, '删除失败', err))
  });
})

/**
 * @function 获取单个信息
 * @author Eric
 * @date 2018-08-01
 * @param meetingid
 */
router.post('/findone', (req, res) => {
  let params = {}
  let id = req.body.id
  if (id) {
    params.id = id;

    literature.findOne({where: params}).then(record => {
      if (record) {
        res.send(reObj(0, '获取成功', record))
      } else {
        res.send(reObj(-1, '获取失败或此记录不存在', {}))
      }
    }).catch(err => {
      res.send(reObj(-1, '获取失败', err))
    });
  } else {
    res.send(reObj(-1, 'id不能为空', []))
  }
})


/**
 * @function 获取所有数据(支持分页，条件过滤)
 * @author Eric
 * @date 2018-07-31
 * @param page,pagerow,meetingname,meetingtype
 */
router.post('/findall',async function(req, res)  {
 /* let meetingname = req.body.meetingname || ''
  let meetingtype = req.body.meetingtype || ''*/
  let params = req.body
  let pagerow = parseInt(req.body.pagerow)
  let page = parseInt(req.body.page)
  //对页码进行容错
  if (pagerow > 999) {
    pagerow = 999
  }
  if (page == 0) {
    page = 1
  }

  //筛选条件
/*  if (meetingname) {
    params.meetingname = {'$like': '%' + meetingname + '%'}
  }
  if (meetingtype) {
    params.meetingtype = meetingtype
  }*/
    let bookparams = {}
    let records=[]
    delete params["page"]
    delete params["pagerow"]
  literature.findAndCountAll({
    order: "sortid DESC",
    limit: pagerow || 100,
    offset: parseInt(pagerow * (page - 1)) || 0,
    where: params
  }).then(record => {
      console.log("rows:"+JSON.stringify(record.rows))
    //  var tasks = [{name:'abc'},{name:'ccc'}];
      async.eachSeries(record.rows, function (item, callback) {
          //console.log(JSON.stringify(item));
               let id = item.bookid

               bookparams.id = id;

               book.findOne({where: bookparams}).then(record => {
                 let tempRecord=JSON.parse(JSON.stringify(record))
                 tempRecord.id=item.id                
                   records.push(tempRecord)
                   callback(null,"success");
               }).catch(err => {
                   res.send(reObj(-1, '获取信息失败', err))
               });


      }, function (err,www) {
          res.send(reObj(0, '获取数据成功', records, record.count))
      });

  }).catch(err => {
    res.send(reObj(-1, '获取数据失败', err))
  });
})

/**
 * @function 获取所有数据(支持分页，条件过滤)
 * @author Eric
 * @date 2018-07-31
 * @param page,pagerow,meetingname,meetingtype
 */
router.get('/findforindex',async function(req, res)  {
  
   let params = {}
   let pagerow = parseInt(req.body.pagerow)
   let page = parseInt(req.body.page)
   //对页码进行容错
   if (pagerow > 999) {
     pagerow = 999
   }
   if (page == 0) {
     page = 1
   }
 
     let cagetoryParams = {}
     let records=[]
     category.findAndCountAll({     
     order: "sortid DESC",
     limit: pagerow || 100,
     offset: parseInt(pagerow * (page - 1)) || 0,
     where: params
   }).then(record => {            
       async.eachSeries(record.rows, function (item, callback) {
           console.log("item:"+JSON.stringify(item));                
                cagetoryParams.category = item.name;
        
                literature.findAndCountAll({order: "sortid DESC",
                limit: pagerow || 3,
                offset: parseInt(pagerow * (page - 1)) || 0,where: cagetoryParams}).then(record => {
                  
                  if(record.count>0)
                  {
                    record.category=item.name
                    records.push(record)
                  }           
                         
                    callback(null,"success");
                }).catch(err => {                    
                });
 
 
       }, function (err,www) {
           res.send(reObj(0, '获取数据成功', records, record.count))
       });
 
   }).catch(err => {
     console.log("err:"+JSON.stringify(err))
     res.send(reObj(-1, '获取数据失败', err))
   });
 })

module.exports = router;
